﻿using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.UI;
using shenghua.Marketing.Coupons;
using shenghua.Order.Orders.Median;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shenghua.Member.Coupons
{
    public class MemberCouponManager: DomainService
    {
        private readonly IRepository<MemberCoupon> _memberCouponRepository;
        private readonly CouponManager _couponManager;

        public MemberCouponManager(
            IRepository<MemberCoupon> memberCouponRepository,
            CouponManager couponManager
            )
        {
            _memberCouponRepository = memberCouponRepository;
            _couponManager = couponManager;
        }

        /// <summary>
        /// 领取优惠券
        /// </summary>
        /// <returns></returns>
        public async Task ReceiveCoupon(Member.Members.Member member, Coupon coupon)
        {
            if(await _couponManager.IsGrantedForMember(member.Id, coupon.Id))
            {
                throw new UserFriendlyException("已经领取过该优惠券");
            }
            await _couponManager.GrantCoupon(coupon, member);
        }

        public async Task<MemberCoupon> Get(long? memberId, int memberCouponId)
        {
            var query = _memberCouponRepository.GetAll();
            if(memberId != null)
            {
                query = query.Where(r => r.MemberId == memberId);
            }
            var item = query.Where(r => r.Id == memberCouponId).FirstOrDefault();
            if(item == null)
            {
                throw new UserFriendlyException("优惠券不存在");
            }
            return item;
        }

        /// <summary>
        /// 得到所有可以使用的优惠券
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public async Task<List<MemberCoupon>> GetCanUsedCoupons(long memberId, List<CommodityCollectionItem> items)
        {
            var now = DateTime.Now;
            var query = _memberCouponRepository.GetAll().Where(r => r.MemberId == memberId);
            query = query.Where(r => now >= r.TimeLimit.Begin && now <= r.TimeLimit.End && r.Status == MemberCouponStatus.Unused);
            var result = query.ToList();
            return result.Where(r => r.CanUse(items)).ToList();
            //return query.Where(r => r.CanUse(items)).ToList();
        }

        /// <summary>
        /// 查看所有优惠券
        /// </summary>
        /// <returns></returns>
        public async Task<List<MemberCoupon>> GetAll(long memberId)
        {
            return await _memberCouponRepository.GetAllListAsync(r => r.MemberId == memberId);
        }

        /// <summary>
        /// 占用优惠券
        /// </summary>
        /// <param name="memberId"></param>
        /// <param name="memberCouponId"></param>
        /// <returns></returns>
        public async Task OccupyCoupon(long? memberId, MemberCoupon memberCoupon)
        {
            if(memberId != null && memberCoupon.MemberId != memberId)
            {
                throw new UserFriendlyException("优惠券不属于该会员");
            }
            if (memberCoupon.IsUsed)
            {
                throw new UserFriendlyException("该优惠券已经被使用了");
            }
            memberCoupon.Status = MemberCouponStatus.Occupied;
        }
        public async Task OccupyCoupon(long? memberId, int memberCouponId)
        {
            var item = await Get(memberId, memberCouponId);
            await OccupyCoupon(memberId, item);
        }

        /// <summary>
        /// 使用优惠券
        /// </summary>
        /// <param name="memberId"></param>
        /// <param name="memberCouponId"></param>
        /// <returns></returns>
        public async Task UseCoupon(long? memberId, MemberCoupon memberCoupon)
        {
            if (memberId != null && memberCoupon.MemberId != memberId)
            {
                throw new UserFriendlyException("优惠券不属于该会员");
            }
            if(memberCoupon.Status == MemberCouponStatus.Used)
            {
                throw new UserFriendlyException("无法使用优惠券，优惠券已经被使用");
            }
            memberCoupon.Status = MemberCouponStatus.Used;
            await _memberCouponRepository.UpdateAsync(memberCoupon);
            await _couponManager.IsUsedByMember(memberCoupon.CouponId);
        }
        public async Task UseCoupon(long? memberId, int memberCouponId)
        {
            var item = await Get(memberId, memberCouponId);
            await UseCoupon(memberId, item);
        }

        /// <summary>
        /// 释放优惠券，即解除对优惠券的占用
        /// </summary>
        /// <param name="member"></param>
        /// <param name="memberCoupon"></param>
        /// <returns></returns>
        public async Task RelieveCoupon(long? memberId, MemberCoupon memberCoupon)
        {
            if (memberId != null && memberCoupon.MemberId != memberId)
            {
                throw new UserFriendlyException("优惠券不属于该会员");
            }
            if (memberCoupon.Status == MemberCouponStatus.Used)
            {
                throw new UserFriendlyException("该优惠券已经被使用了");
            }
            memberCoupon.Status = MemberCouponStatus.Unused;
        }
        public async Task RelieveCoupon(long? memberId, int memberCouponId)
        {
            var item = await Get(memberId, memberCouponId);
            await RelieveCoupon(memberId, item);
        }

        public async Task DeleteCoupon(int memberCouponId)
        {
            await _memberCouponRepository.DeleteAsync(memberCouponId);
        }
    }
}
